package huu.phong.googlemusic;

import java.awt.Color;
import java.awt.Component;
import java.util.ArrayDeque;
import java.util.Queue;

import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;

public class AlbumListRenderer extends DefaultListCellRenderer {

	private static final long serialVersionUID = -8767313895823810373L;
	public static final ImageIcon DEFAULT_ALBUM_ART = new ImageIcon(Album.class.getResource("/images/album_art.jpg"));
	Color line = new Color(238, 238, 238);
	Color selected = new Color(51, 153, 255);
	Thread loadImages;
	Queue<Thread> process = new ArrayDeque<Thread>();
	
	public AlbumListRenderer(){
		loadImages = new Thread(){
			public void run(){
				while (true){
					while (!process.isEmpty()){
						Thread thread = process.poll();
						thread.start();
						try {
							thread.join();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		loadImages.start();
	}
	
	public Component getListCellRendererComponent(final JList list, Object value,
			int index, boolean isSelected, boolean cellHasFocus) {
		final JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, false);
		label.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, line));
		final Album album = (Album) value;
		if (album.albumArt != null && !album.albumArt.equals("")){
			if (album.file != null){
				label.setIcon(new ImageIcon(album.file));
			}else{
				label.setIcon(DEFAULT_ALBUM_ART);
				process.add(new Thread(){
					public void run(){
						album.saveImage();
						label.setIcon(new ImageIcon(album.file));
						list.repaint();
					}
				});
			}
		}else{
			label.setIcon(DEFAULT_ALBUM_ART);
		}
		if (isSelected){
			label.setBackground(selected);
		}else{
			label.setBackground(Color.WHITE);
		}
		label.setOpaque(true);
		return label;
	}
}
